
package com.platform.security.util;


import com.platform.security.exception.UnauthorizedExceptionBase;
import com.platform.security.service.SysUserDetails;
import com.platform.security.service.UserConnect;
import lombok.experimental.UtilityClass;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * 安全工具类
 */
@UtilityClass
public class SecurityUtils {
    /**
     * 获取Authentication
     */
    public Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取用户
     */
    public UserConnect getUser() {
        Authentication authentication = getAuthentication();
        Object principal = authentication.getPrincipal();
        if (principal instanceof UserConnect) {
            return (UserConnect) principal;
        }
        throw new UnauthorizedExceptionBase("无法获取普通用户信息");
    }

    /**
     * 获取系统用户
     */
    public SysUserDetails getSysUser() {
        Authentication authentication = getAuthentication();
        Object principal = authentication.getPrincipal();
        if (principal instanceof SysUserDetails) {
            return (SysUserDetails) principal;
        }
        throw new UnauthorizedExceptionBase("无法获取系统用户信息");
    }
}
